package com.dgw.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dgw.entity.User;
import com.dgw.enums.ResultEnum;
import com.dgw.exception.MyException;
import com.dgw.service.LoginService;
import com.dgw.utils.CookieUtils;
import com.dgw.utils.Result;
import com.dgw.utils.ResultUtil;
import com.dgw.utils.StringUtil;

@Controller
public class LoginController {
	
	
	private static final String cookieName="TOKEN";
	
	@Autowired
	private LoginService loginService;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(String callbackUrl,Model model){
		model.addAttribute("callbackUrl", callbackUrl);
		return "login";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Result<String> doLogin(HttpServletRequest request,HttpServletResponse response,String username,String password){
		User user = loginService.login(username, password);
		if(user==null){
			throw new MyException(ResultEnum.LOGIN_FAIL);
		}
		request.getSession().setAttribute("user", user);
		String callbackUrl=request.getContextPath()+"/home";
		
		return ResultUtil.success(callbackUrl);
	}
}
